package com.swingolf.dao.hrd;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.swingolf.dao.ImageDAO;
import com.swingolf.model.Image;
import org.apache.geronimo.mail.util.Base64;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * The <code>HRDTemperatureDAOImpl</code> provides crud methods for accessing collecting temperatures.
 */
@Repository
public class HRDImageDAOImpl implements ImageDAO {


  @Override
  public void delete(Image entity) {

  }

  @Override
  public void update(Image entity) {

  }

  @Override
  public void save(Image image) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity imageEntity = new Entity("Image");
    imageEntity.setProperty("content", new Text(new String(Base64.encode(image.getImage()))));
    Key key = datastore.put(imageEntity);
    image.setId(key.getId());
  }

  @Override
  public Image findById(Long id) {
    Collection<Image> images = findAll();
    for (Image image : images) {
      if (image.getId().equals(id)) {
        return image;
      }
    }
    return null;
  }

  @Override
  public List<Image> findAll() {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query q = new Query("Image");
    PreparedQuery pq = datastore.prepare(q);
    List<Image> result = new LinkedList<Image>();
    Iterable<Entity> iterable = pq.asIterable();
    for (Entity entity : iterable) {
      Text imageText = ((Text) entity.getProperty("content"));
      String image = imageText == null ? null : imageText.getValue();
      try {
        result.add(new Image(entity.getKey().getId(), Base64.decode(image.getBytes())));
      } catch (Exception ex) {
      }
    }
    return result;

  }

  private void deleteAll() {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  }
}
